/**
 * 
 */
package com.cms.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cms.model.CpInfo;
import com.cms.service.CpInfoService;
import com.cms.service.CpInfoServiceImpl;
import com.util.Singleton;

/**
 * @author jinmei.wang
 *
 */
public class CpInfoManager extends Singleton {
	
	private CpInfoService service = null;
	private Map<Integer, CpInfo> map = null;
	private List<CpInfo> list = null;
	
	public static void main (String[] argv)
	{
	}
	
	public static CpInfoManager getInstance()
	{
		return (CpInfoManager) CpInfoManager.getInstance(CpInfoManager.class.getName());
	}
	public CpInfoManager()
	{
		map = new HashMap<Integer, CpInfo>();
		list = new ArrayList<CpInfo>();
		service = new CpInfoServiceImpl();
		for (CpInfo p : service.getCpInfos())
		{
			map.put(p.getId(), p);
			list.add(p);
		}
	}
	
	public CpInfo getCpInfo(int id)
	{
		return map.get(id);
	}
	
	public List<CpInfo> getCpInfos()
	{
		return list;
	}
	
	public boolean saveCpInfo(String type, CpInfo cpInfo)
	{
		if (service.saveCpInfo(cpInfo, type))
		{
			if (type.equals("insert"))
			{
				map.put(cpInfo.getId(), cpInfo);
				list.add(cpInfo);
			}
			else if (type.equals("delete"))
			{
				map.remove(cpInfo.getId());
				for (int n = 0; n < list.size(); n++)
				{
					if (list.get(n).getId() == cpInfo.getId())
					{
						list.remove(n);
						break;
					}
				}
			}
			else // if (type.equals("update")) // online offline
			{
				map.put(cpInfo.getId(), cpInfo);
				for (int n = 0; n < list.size(); n++)
				{
					if (list.get(n).getId() == cpInfo.getId())
					{
						list.set(n, cpInfo);
						break;
					}
				}
			}
			return true;
		}
		return false;
	}
	
}
